package com.tacademy.jmtwitter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class TwitterApi {
	public final static String CONSUMER_KEY = "EJWL7eQDXfk4j4atpqR4KQ";
	public final static String CONSUMER_SECRET = "bqUgYvFO3OtSsGjfh6FhvFi0Y9ujN8TVIRTNKGI";
	public final static String REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token";
	public final static String AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize";
	public final static String ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
	public final static String CALLBACK_URL = "twit://twitlecture.com";

	CommonsHttpOAuthConsumer mConsumer;

	public TwitterApi(String token, String tokenSecret) {
		mConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
		mConsumer.setTokenWithSecret(token, tokenSecret);

	}
	Status reTweet(long replyToStatusId) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException{
		HttpClient client = new DefaultHttpClient();
		
		HttpPost post = new HttpPost("http://api.twitter.com/1/statuses/retweet/"+replyToStatusId+".xml");//post는 URL 에 데이터 넣지 않음
		
		Log.e("TwitterApi", "리트윗 시작");
		
		/////////////////////////밑 세줄//////////프로토콜 속성 변경  setUseExpectContinue
		HttpParams hp = new BasicHttpParams();
		HttpProtocolParams.setUseExpectContinue(hp, false);
		post.setParams(hp);
		//////////////////////////////////////////////////////////////////////////////////////////////
		Status stat = null;
		try {
			mConsumer.sign(post);
			HttpResponse response = client.execute(post);// 중요!!!! 여기서 전송함
			
			StatusLine status = response.getStatusLine();
			Log.e("TwitterApi", "Status Code : " + status.getStatusCode());
			if (status.getStatusCode() == 200) {
				// ok
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
				XmlPullParserFactory factory;
				factory = XmlPullParserFactory.newInstance();
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(is, "UTF-8");
				stat = new Parser().parseStatus(xpp);
				// stat array
				is.close();
				Log.e("tc", "Status Code : " + status.getStatusCode());
			} else {
				// Error
				InputStream is = response.getEntity().getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));

				String s;
				Log.e("tc", "Status Code : " + status.getStatusCode());
				while ((s = br.readLine()) != null) {
					Log.e("tc", s);
				}
				br.close();

			}
		} catch (ClientProtocolException e) {
			Log.e("tc", e.getMessage());
		} catch (IOException e) {

			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (OAuthException e) {
			Log.e("tc", e.getMessage());
		}
		
		
		return stat;
		
	}
	Status statusUpdate(String text, long replyToStatusId) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException{
		HttpClient client = new DefaultHttpClient();
		
		HttpPost post = new HttpPost("https://api.twitter.com/1/statuses/update.xml");//post는 URL 에 데이터 넣지 않음
		
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("status", text));
		if(replyToStatusId != 0){
			params.add(new BasicNameValuePair("in_reply_to_status_id", String.valueOf(replyToStatusId)));
		}
		
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"UTF-8");
		post.setEntity(formEntity);
		
		/////////////////////////밑 세줄//////////프로토콜 속성 변경  setUseExpectContinue
		HttpParams hp = new BasicHttpParams();
		HttpProtocolParams.setUseExpectContinue(hp, false);
		post.setParams(hp);
		//////////////////////////////////////////////////////////////////////////////////////////////
		Status stat = null;
		try {
			mConsumer.sign(post);
			HttpResponse response = client.execute(post);// 중요!!!! 여기서 전송함
			
			StatusLine status = response.getStatusLine();
			Log.e("tc", "Status Code : " + status.getStatusCode());
			if (status.getStatusCode() == 200) {
				// ok
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
				XmlPullParserFactory factory;
				factory = XmlPullParserFactory.newInstance();
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(is, "UTF-8");
				stat = new Parser().parseStatus(xpp);
				// stat array
				is.close();
				Log.e("tc", "Status Code : " + status.getStatusCode());
			} else {
				// Error
				InputStream is = response.getEntity().getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));

				String s;
				Log.e("tc", "Status Code : " + status.getStatusCode());
				while ((s = br.readLine()) != null) {
					Log.e("tc", s);
				}
				br.close();

			}
		} catch (ClientProtocolException e) {
			Log.e("tc", e.getMessage());
		} catch (IOException e) {

			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (OAuthException e) {
			Log.e("tc", e.getMessage());
		}
		
		
		return stat;
		
	}
	
	
	
	User verifyCredentials() {

		HttpClient client = new DefaultHttpClient();

		HttpGet get = null;
		User user = new User();
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

		try {
//			String query = URLEncodedUtils.format(params, "UTF-8");
			URI u = URIUtils.createURI("https", "api.twitter.com", -1,
					"/1/account/verify_credentials.xml", null, null);
			get = new HttpGet(u);
			Log.d("TwitterApi", "u값 어떻게 받니?" + u.toString());

		} catch (URISyntaxException e) {
			Log.e("TwitterApi", "URI Error");

		}
		Log.d("TwitterApi", "Try 끝 ");

		try {
			mConsumer.sign(get);
			HttpResponse response = client.execute(get);// 중요!!!! 여기서 전송함

			StatusLine status = response.getStatusLine();
			Log.e("TwitterApi", "Status Code : " + status.getStatusCode());
			if (status.getStatusCode() == 200) {
				// ok
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
//				wirteToExternal(is);
				Log.e("TwitterApi", "파싱시작");
				XmlPullParserFactory factory;
				factory = XmlPullParserFactory.newInstance();
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(is, "UTF-8");
				user = new Parser().parseUser(xpp);
				// stat array
				is.close();
				Log.d("TwitterApi", "Status Code : " + status.getStatusCode());
				Log.d("TwitterApi", "리턴유저 ");
				
			} else {
				// Error
				InputStream is = response.getEntity().getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));

				String s;
				Log.e("TwitterApi", "Status Code : " + status.getStatusCode());
				while ((s = br.readLine()) != null) {
					Log.e("TwitterApi", s);
				}
				br.close();

				return null;
			}
		} catch (ClientProtocolException e) {
			Log.e("tc", e.getMessage());
			 // error
		} catch (IOException e) {

			e.printStackTrace();
			 // error
		} catch (XmlPullParserException e) {
			e.printStackTrace();
			 // error
		} catch (OAuthException e) {
			Log.e("tc", e.getMessage());
			 // error
		}
		
		return user;
		// ok user

	}

	ArrayList<Status> getHomeTimeline(int count, long siceId, long maxId) {

		// Authorization이 필요하므로 Token으로 Sign해서 Request 보낸다.!!

		ArrayList<Status> arrlist = null;
		HttpClient client = new DefaultHttpClient();

		HttpGet get = null;
		Log.d("tc", "get찍힙니까?");
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

		if (count != 0) {
			params.add(new BasicNameValuePair("count", String.valueOf(count)));
			Log.d("tc", "카운트");
		}
		if (siceId != 0) {
			params.add(new BasicNameValuePair("since_id", String
					.valueOf(siceId)));

		}
		if (maxId != 0) {
			params.add(new BasicNameValuePair("max_id", String.valueOf(maxId)));

		}

		try {
			String query = URLEncodedUtils.format(params, "UTF-8");
			URI u = URIUtils.createURI("https", "api.twitter.com", -1,
					"/1/statuses/home_timeline.xml", query, null);
			get = new HttpGet(u);
			Log.d("tc", "u값 어떻게 받니?" + u.toString());

		} catch (URISyntaxException e) {
			Log.e("tc", "URI Error");

		}
		Log.d("tc", "Try 끝 ");

		try {
			mConsumer.sign(get);
			HttpResponse response = client.execute(get);// 중요!!!! 여기서 전송함

			StatusLine status = response.getStatusLine();
			Log.e("tc", "Status Code : " + status.getStatusCode());
			if (status.getStatusCode() == 200) {
				// ok
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
				XmlPullParserFactory factory;
				factory = XmlPullParserFactory.newInstance();
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(is, "UTF-8");
				arrlist = new Parser().getParse(xpp);
				// stat array
				is.close();
				Log.e("tc", "Status Code : " + status.getStatusCode());
			} else {
				// Error
				InputStream is = response.getEntity().getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));

				String s;
				Log.e("tc", "Status Code : " + status.getStatusCode());
				while ((s = br.readLine()) != null) {
					Log.e("tc", s);
				}
				br.close();

			}
		} catch (ClientProtocolException e) {
			Log.e("tc", e.getMessage());
		} catch (IOException e) {

			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (OAuthException e) {
			Log.e("tc", e.getMessage());
		}

		return arrlist;
	}

	// ArrayList<Status> getPublicTimeline() {
	// //TODO
	// }
	ArrayList<Status> getUserTimeline(String screenName, int count,
			long siceId, long maxId) {
		ArrayList<Status> arrlist = null;
		HttpClient client = new DefaultHttpClient();

		HttpGet get = null;
		Log.d("tc", "get찍힙니까?");
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("screen_name", screenName));

		if (count != 0) {
			params.add(new BasicNameValuePair("count", String.valueOf(count)));
			Log.d("tc", "카운트");
		}
		if (siceId != 0) {
			params.add(new BasicNameValuePair("since_id", String
					.valueOf(siceId)));

		}
		if (maxId != 0) {
			params.add(new BasicNameValuePair("max_id", String.valueOf(maxId)));

		}

		try {
			String query = URLEncodedUtils.format(params, "UTF-8");
			URI u = URIUtils.createURI("http", "api.twitter.com", -1,
					"/1/statuses/user_timeline.xml", query, null);
			get = new HttpGet(u);
			Log.d("tc", "u값 어떻게 받니?" + u.toString());

		} catch (URISyntaxException e) {
			Log.e("tc", "URI Error");

		}
		Log.d("tc", "Try 끝 ");

		try {
			mConsumer.sign(get);
			HttpResponse response = client.execute(get);// 중요!!!! 여기서 전송함

			StatusLine status = response.getStatusLine();
			Log.e("tc", "Status Code : " + status.getStatusCode());
			if (status.getStatusCode() == 200) {
				// ok
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
				XmlPullParserFactory factory;
				factory = XmlPullParserFactory.newInstance();
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(is, "UTF-8");
				arrlist = new Parser().getParse(xpp);
				// stat array
				is.close();
				Log.e("tc", "Status Code : " + status.getStatusCode());
			} else {
				// Error
				InputStream is = response.getEntity().getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));

				String s;
				Log.e("tc", "Status Code : " + status.getStatusCode());
				while ((s = br.readLine()) != null) {
					Log.e("tc", s);
				}
				br.close();
				// TODO return null;
			}
		} catch (ClientProtocolException e) {
			Log.e("tc", e.getMessage());
		} catch (IOException e) {

			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (OAuthException e) {
			Log.e("tc", e.getMessage());
		}

		return arrlist;

	}

	static Bitmap getPrfileImageBitmap(String url) {
		InputStream is = null;
		try {
			URL u = new URL(url);
			URLConnection con = u.openConnection();
			is = con.getInputStream();

			Bitmap bitmap = BitmapFactory.decodeStream(is);
			return bitmap;
		} catch (IOException e) {
			Log.d("ta", "Bitmap Download Error" + e.getMessage());
			return null;
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		}
	}

	public void wirteToExternal(InputStream is) {
		File external = Environment.getExternalStorageDirectory();
		try {
			FileOutputStream fo = new FileOutputStream(external.getPath()
					+ "/jm.xml");
			byte[] buf = new byte[1024];
			int len;
			while ((len = is.read(buf)) != -1) {

				fo.write(buf, 0, len);
			}
			fo.close();
			Log.e("TwitterApi", "저장완료");
		} catch (IOException e) {

			Log.d("TwitterApi", "write External Error" + e.getMessage());
		}

	}

}
